/*
 * taskqueue.h
 *
 *  Created on: 2011-5-25
 *      Author: chenl
 */

#ifndef TASKQUEUE_H_
#define TASKQUEUE_H_

#include "common/common_err.h"
#include "global.h"

#include <deque>

class CTask;

Interface ITaskQueue
{
	virtual ~ITaskQueue(){}
	virtual int32_t Initialize() = 0;
	virtual int32_t Uninitialize() = 0;
	virtual int32_t InsertTask(CTask&) = 0;
	virtual int32_t DeleteTask(CTask&) = 0;
	virtual int32_t MoveTaskToTail(CTask&) = 0;
	virtual bool IsTaskOnQueue(const CTask&) = 0;
	virtual bool IsEmtpy() const = 0;
	virtual bool IsFull() const = 0;
	virtual CTask* Pop() = 0;
	virtual CTask* FirstTask() = 0;
	virtual CTask* NextTask(CTask&) = 0;

};

class CTaskQueue : public ITaskQueue
{
public:
	typedef std::deque<CTask*, DEFAULT_ALLOC<CTask*> > TaskQueue;
	typedef TaskQueue::iterator 		TaskQueueItr;
	typedef TaskQueue::const_iterator 	ConstTaskQueueItr;
public:
	CTaskQueue();
	virtual ~CTaskQueue();

public:
	virtual int32_t Initialize()
	{
		return S_OK;
	}
	virtual int32_t Uninitialize()
	{
		return S_OK;
	}
	virtual int32_t InsertTask(CTask& task)
	{
		taskQueue.push_back(&task);
		return S_OK;
	}
	virtual int32_t DeleteTask(CTask&);

	virtual int32_t MoveTaskToTail(CTask&);

	virtual bool IsTaskOnQueue(const CTask& task)
	{
		return taskQueue.end() != FindTask(task);
	}
	virtual bool IsEmtpy() const
	{
		return taskQueue.empty();
	}
	virtual bool IsFull() const
	{
		return false;
	}
	virtual CTask* Pop()
	{
		CTask* task = taskQueue.front();
		taskQueue.pop_front();
		return task;
	}
	virtual CTask* FirstTask()
	{
		if (taskQueue.empty())
			return NULL;
		return taskQueue.front();
	}
	virtual CTask* NextTask(CTask& task)
	{
		if(IsEmtpy())
		{
			return NULL;
		}
		TaskQueueItr itr = FindTask(task);
		if (taskQueue.end() == itr)
		{
			return NULL;
		}
		if(taskQueue.end() == (++itr))
		{
			return NULL;
		}
		return *itr;
	}

	TaskQueueItr FindTask(const CTask& task);

public:
	TaskQueue taskQueue;
};

#endif /* TASKQUEUE_H_ */
